# -*- coding:utf-8 -*-
"""
Created on 7 Dec 2009
"""
__author__ = 'Ilias Karampatsos'


import time

def retry(ExceptionToCheck, tries=4, delay=3, backoff=2):
    """Retry decorator
    original from http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
    """
    def deco_retry(f):
        def f_retry(*args, **kwargs):
            mtries, mdelay = tries, delay
            try_one_last_time = True
            while mtries > 1:
                try:
                    f(*args, **kwargs)
                    try_one_last_time = False
                    break
                except ExceptionToCheck, e:
                    print "%s, Retrying in %d seconds..." % (str(e), mdelay)
                    time.sleep(mdelay)
                    mtries -= 1
                    mdelay *= backoff
            if try_one_last_time:
                f(*args, **kwargs)
            return
        return f_retry # true decorator
    return deco_retry

if __name__=='__main__':
    import random
    
    @retry(Exception, tries=4)
    def test_random(text):
        x = random.random()
        if x < 0.5:
            raise Exception("Fail")
        else:
            print "Success: ", text
    test_random("it works!")